package com.ywu.api.service.standard.service;

import com.ywu.api.service.standard.data.ApiServiceRepository;
import com.ywu.api.service.standard.dto.ApiServiceInfoDto;
import com.ywu.api.service.standard.entity.ApiServiceInfoEntity;
import com.ywu.api.service.standard.vo.ApiServiceInfoVo;
import com.ywu.boot.context.YwuContextHolder;
import com.ywu.common.entity.PageList;
import com.ywu.common.gson.GsonUtils;
import com.ywu.common.page.PageService;
import com.ywu.common.result.CommonResult;
import com.ywu.common.utils.TimerIdGenerateUtil;
import com.ywu.service.spi.dto.ServiceDto;
import com.ywu.service.spi.entity.ServiceEntity;
import com.ywu.service.spi.spi.ServiceSpi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @ClassName ApiServiceInfoService
 * @Description TODO
 * @Author GroundDemo
 * @Date 2025/8/9 9:42
 * @Version 1.0
 **/
@Service
public class ApiServiceInfoService {
    @Autowired
    private ApiServiceRepository repository;

    @Autowired
    private ServiceSpi serviceSpi;

    /**
    * @Author GroundDemo
    * @Description 根据编码校验数据是否存在
    * @Date 9:47 2025/8/9
    * @Param [code]
    * @return boolean
    **/
    private boolean checkEntityIsExistByCode(String code) {
        ApiServiceInfoEntity search = new ApiServiceInfoEntity();
        search.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        search.setApiServiceCode(code);
        ApiServiceInfoEntity entity = repository.getEntity(search);
        return !Objects.isNull(entity);
    }

    /**
    * @Author GroundDemo
    * @Description 根据Id校验数据是否存在
    * @Date 9:52 2025/8/9
    * @Param [id]
    * @return boolean
    **/
    private boolean checkEntityIsExistById(String id) {
        ApiServiceInfoEntity search = new ApiServiceInfoEntity();
        search.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        search.setId(id);
        ApiServiceInfoEntity entity = repository.getEntity(search);
        return !Objects.isNull(entity);
    }

    /**
    * @Author GroundDemo
    * @Description 添加接口服务模板
    * @Date 9:43 2025/8/9
    * @Param [dto]
    * @return java.lang.Object
    **/
    public CommonResult<Object> createApiServiceInfo(ApiServiceInfoDto dto) {
        // 校验编码是否存在
        if (checkEntityIsExistByCode(dto.getApiServiceCode())) {
            return CommonResult.error().setErrorCode("api.service.code.has.exist").setMessage("服务模板编码已存在");
        }
        // 构建插入对象
        ApiServiceInfoEntity insert = new ApiServiceInfoEntity();
        BeanUtils.copyProperties(dto, insert);
        insert.setId(TimerIdGenerateUtil.nextId());
        insert.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        insert.createInfo(YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount());
        repository.addApiServiceEntity(insert);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 修改服务接口
    * @Date 9:51 2025/8/9
    * @Param [dto]
    * @return java.lang.Object
    **/
    public CommonResult<Object> updateApiServiceInfo(ApiServiceInfoDto dto) {
        // 判断当前ID是否存在
        if (!checkEntityIsExistById(dto.getId())) {
            return CommonResult.error().setErrorCode("api.service.id.not.exist").setMessage("服务模板不存在");
        }
        ApiServiceInfoEntity update = new ApiServiceInfoEntity();
        BeanUtils.copyProperties(dto, update);
        update.updateInfo(YwuContextHolder.getCurrentContext().getYwuContextUser().getUserAccount());
        repository.updateApiServiceEntity(update);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 刪除服务接口模板
    * @Date 9:55 2025/8/9
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> deleteApiServiceInfo(ApiServiceInfoDto dto) {
        // 判断当前ID是否存在
        if (!checkEntityIsExistById(dto.getId())) {
            return CommonResult.error().setErrorCode("api.service.id.not.exist").setMessage("服务模板不存在");
        }
        ApiServiceInfoEntity delete = new ApiServiceInfoEntity();
        delete.setId(dto.getId());
        repository.deleteApiService(delete);
        return CommonResult.success(null);
    }

    /**
    * @Author GroundDemo
    * @Description 分页查询接口模板
    * @Date 9:57 2025/8/9
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryPageList(ApiServiceInfoDto dto) {
        // 设置当前租户ID
        dto.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        // 查询总数量
        int count = repository.queryPageCount(dto);
        // 配置分页参数
        PageService.execPageStartAndEnd(dto.getPageInfo());
        // 查询分页列表
        List<ApiServiceInfoEntity> entityList = repository.queryPageList(dto);
        List<ApiServiceInfoVo> voList = new ArrayList<>();
        // 存储应用id与名称的关联关系
        Map<String, String> applicationIdMap = new HashMap<>();
        // 填充用户名称
        for (ApiServiceInfoEntity entity : entityList) {
            ApiServiceInfoVo apiServiceInfoVo = new ApiServiceInfoVo();
            BeanUtils.copyProperties(entity, apiServiceInfoVo);
            if (applicationIdMap.containsKey(entity.getApplicationId())) {
                apiServiceInfoVo.setApplicationName(applicationIdMap.get(entity.getApplicationId()));
            } else {
                ServiceDto search = new ServiceDto();
                search.setId(Integer.valueOf(entity.getApplicationId()));
                CommonResult<Object> allApplication = serviceSpi.getAllApplication(search);
                Object data = allApplication.getData();
                String serialize = GsonUtils.serialize(data);
                List<ServiceEntity> serviceEntities = GsonUtils.deserializeList(serialize, ServiceEntity.class);
                if (CollectionUtils.isEmpty(serviceEntities)) {
                    apiServiceInfoVo.setApplicationName("未知");
                    applicationIdMap.put(entity.getApplicationId(), "未知");
                } else {
                    apiServiceInfoVo.setApplicationName(serviceEntities.get(0).getApplicationName());
                    applicationIdMap.put(entity.getApplicationId(), serviceEntities.get(0).getApplicationName());
                }
            }
            voList.add(apiServiceInfoVo);
        }
        // 构建分页对象
        PageList<ApiServiceInfoVo> resPageList = new PageList<>(dto.getPageInfo().getPageIndex(), dto.getPageInfo().getPageSize(),
                count, voList);
        return CommonResult.success(resPageList);
    }

    /**
    * @Author GroundDemo
    * @Description 根据应用ID查询服务接口
    * @Date 10:01 2025/8/9
    * @Param [dto]
    * @return com.ywu.common.result.CommonResult<java.lang.Object>
    **/
    public CommonResult<Object> queryApiServiceByApplicationId(ApiServiceInfoDto dto) {
        // 构建查询对象
        ApiServiceInfoEntity search = new ApiServiceInfoEntity();
        search.setTenantId(YwuContextHolder.getCurrentContext().getYwuContextTenant().getTenantId());
        search.setApplicationId(dto.getApplicationId());
        List<ApiServiceInfoEntity> entityList = repository.queryApiServiceByApplicationId(search);
        return CommonResult.success(entityList);
    }
}
